<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AGV任务下发系统</title>
    <style>
        :root {
            --primary-color: #4a6cf7;
            --primary-dark: #3a5bd9;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --bg-color: #f8f9fa;
            --card-bg: #ffffff;
            --text-color: #212529;
            --border-color: #dee2e6;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        .dark-mode {
            --primary-color: #5d7df9;
            --primary-dark: #4a6cf7;
            --secondary-color: #8a93a2;
            --bg-color: #121212;
            --card-bg: #1e1e1e;
            --text-color: #e0e0e0;
            --border-color: #333333;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, var(--bg-color) 0%, #e9ecef 100%);
            color: var(--text-color);
            min-height: 100vh;
            transition: var(--transition);
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 20px;
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: var(--shadow);
        }

        h1 {
            font-size: 28px;
            font-weight: 600;
            background: linear-gradient(135deg, var(--primary-color), #6c5ce7);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .theme-toggle {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: var(--transition);
        }

        .theme-toggle:hover {
            transform: rotate(15deg);
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .card {
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: var(--shadow);
            padding: 25px;
            margin-bottom: 25px;
            transition: var(--transition);
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-color);
        }

        select, input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: var(--card-bg);
            color: var(--text-color);
            font-size: 16px;
            transition: var(--transition);
        }

        select:focus, input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.2);
        }

        .btn {
            padding: 12px 25px;
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn:disabled {
            background: var(--secondary-color);
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .error {
            color: var(--danger-color);
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        .response-box {
            background: var(--card-bg);
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            border: 1px solid var(--border-color);
            max-height: 200px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 14px;
            white-space: pre-wrap;
            display: none;
        }

        .debug-toggle {
            background: none;
            border: none;
            color: var(--primary-color);
            cursor: pointer;
            margin-top: 10px;
            font-size: 14px;
            text-decoration: underline;
        }

        .debug-info {
            display: none;
            background: var(--card-bg);
            border-radius: 8px;
            padding: 15px;
            margin-top: 10px;
            border: 1px solid var(--border-color);
            font-family: monospace;
            font-size: 14px;
            white-space: pre-wrap;
        }

        footer {
            text-align: center;
            margin-top: 40px;
            padding: 20px;
            color: var(--secondary-color);
            font-size: 14px;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: var(--card-bg);
            padding: 30px;
            border-radius: 12px;
            max-width: 500px;
            width: 90%;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        .modal h2 {
            margin-bottom: 15px;
            color: var(--primary-color);
        }

        .modal p {
            margin-bottom: 20px;
            line-height: 1.5;
        }

        .shelf-lock {
            color: var(--warning-color);
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: var(--secondary-color);
        }

        .error-message {
            background: var(--danger-color);
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1 id="page-title">AGV任务下发系统</h1>
            <div class="theme-toggle" id="theme-toggle">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 16C14.2091 16 16 14.2091 16 12C16 9.79086 14.2091 8 12 8C9.79086 8 8 9.79086 8 12C8 14.2091 9.79086 16 12 16Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M12 2V4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M12 20V22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M4.93 4.93L6.34 6.34" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M17.66 17.66L19.07 19.07" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M2 12H4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M20 12H22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M6.34 17.66L4.93 19.07" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M19.07 4.93L17.66 6.34" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
        </header>

        <div id="loading-message" class="loading">
            正在加载配置文件...
        </div>

        <div id="error-message" class="error-message" style="display: none;">
            加载配置文件失败，请检查config.json文件是否存在且格式正确。
        </div>

        <div id="main-content" style="display: none;">
            <div class="card">
                <div class="form-group">
                    <label for="area-select">选择区域</label>
                    <select id="area-select">
                        <option value="">请选择区域</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="task-select">任务模板</label>
                    <select id="task-select">
                        <option value="">请先选择区域</option>
                    </select>
                </div>

                <div class="form-group" id="shelf-group">
                    <label for="shelf-input">货架号</label>
                    <input type="text" id="shelf-input" placeholder="请输入货架号">
                    <div class="error" id="shelf-error">请输入货架号</div>
                    <div class="shelf-lock" id="shelf-lock">此货架在5分钟内已下发过任务，请勿重复下发</div>
                </div>

                <div class="form-group" id="task-path-group">
                    <label for="task-path-select">任务路径</label>
                    <select id="task-path-select">
                        <option value="">请选择任务路径</option>
                    </select>
                    <div class="error" id="task-path-error">请选择任务路径</div>
                </div>

                <button class="btn" id="submit-btn">下发任务</button>
                <button class="debug-toggle" id="debug-toggle">查看发送的报文</button>
                <div class="debug-info" id="debug-info"></div>
            </div>

            <div class="card">
                <h3>响应信息</h3>
                <div class="response-box" id="response-box"></div>
            </div>
        </div>

        <footer id="footer-text">
            任务下发系统 © 2025 | 运营 AGV 组提供技术支持
        </footer>
    </div>

    <div class="modal" id="success-modal">
        <div class="modal-content">
            <h2>下发成功</h2>
            <p>任务已成功下发，请勿重复下发。</p>
            <button class="btn" id="modal-close">确定</button>
        </div>
    </div>

    <script>
        // 存储已下发任务的货架和时间
        const shelfHistory = {};

        // DOM元素
        let areaSelect, taskSelect, shelfGroup, shelfInput, shelfError, shelfLock;
        let taskPathGroup, taskPathSelect, taskPathError, submitBtn;
        let responseBox, debugToggle, debugInfo, successModal, modalClose;
        let themeToggle, pageTitle, footerText;
        let loadingMessage, errorMessage, mainContent;

        // 配置数据（将从config.json加载）
        let config = null;

        // 初始化页面
        async function initPage() {
            // 获取DOM元素
            areaSelect = document.getElementById('area-select');
            taskSelect = document.getElementById('task-select');
            shelfGroup = document.getElementById('shelf-group');
            shelfInput = document.getElementById('shelf-input');
            shelfError = document.getElementById('shelf-error');
            shelfLock = document.getElementById('shelf-lock');
            taskPathGroup = document.getElementById('task-path-group');
            taskPathSelect = document.getElementById('task-path-select');
            taskPathError = document.getElementById('task-path-error');
            submitBtn = document.getElementById('submit-btn');
            responseBox = document.getElementById('response-box');
            debugToggle = document.getElementById('debug-toggle');
            debugInfo = document.getElementById('debug-info');
            successModal = document.getElementById('success-modal');
            modalClose = document.getElementById('modal-close');
            themeToggle = document.getElementById('theme-toggle');
            pageTitle = document.getElementById('page-title');
            footerText = document.getElementById('footer-text');
            loadingMessage = document.getElementById('loading-message');
            errorMessage = document.getElementById('error-message');
            mainContent = document.getElementById('main-content');

            try {
                // 从config.json加载配置
                const response = await fetch('config.json');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                config = await response.json();
                
                // 隐藏加载消息，显示主内容
                loadingMessage.style.display = 'none';
                mainContent.style.display = 'block';
                
                // 设置页面标题和页脚
                pageTitle.textContent = config.general.title;
                footerText.textContent = config.general.footer_text;
                
                // 填充区域选择
                for (const area in config.areas) {
                    const option = document.createElement('option');
                    option.value = area;
                    option.textContent = area;
                    areaSelect.appendChild(option);
                }
                
                // 事件监听
                areaSelect.addEventListener('change', updateTaskOptions);
                taskSelect.addEventListener('change', updateFormFields);
                submitBtn.addEventListener('click', submitTask);
                debugToggle.addEventListener('click', toggleDebugInfo);
                modalClose.addEventListener('click', closeModal);
                themeToggle.addEventListener('click', toggleTheme);
                
                // 检查本地存储的主题偏好
                if (localStorage.getItem('darkMode') === 'true') {
                    document.body.classList.add('dark-mode');
                }
                
                // 初始隐藏货架号和任务路径组
                shelfGroup.style.display = 'none';
                taskPathGroup.style.display = 'none';
            } catch (error) {
                console.error('加载配置文件失败:', error);
                loadingMessage.style.display = 'none';
                errorMessage.style.display = 'block';
            }
        }

        // 更新任务选项
        function updateTaskOptions() {
            const area = areaSelect.value;
            taskSelect.innerHTML = '<option value="">请选择任务模板</option>';
            
            if (area && config.areas[area]) {
                const tasks = config.areas[area].tasks;
                for (const taskName in tasks) {
                    const option = document.createElement('option');
                    option.value = taskName;
                    option.textContent = taskName;
                    taskSelect.appendChild(option);
                }
            }
            
            // 重置表单字段
            updateFormFields();
        }

        // 更新表单字段显示
        function updateFormFields() {
            const area = areaSelect.value;
            const taskName = taskSelect.value;
            
            // 隐藏错误信息
            shelfError.style.display = 'none';
            taskPathError.style.display = 'none';
            shelfLock.style.display = 'none';
            
            if (area && taskName && config.areas[area] && config.areas[area].tasks[taskName]) {
                const task = config.areas[area].tasks[taskName];
                
                // 显示或隐藏货架号输入
                if (task.requires_shelf) {
                    shelfGroup.style.display = 'block';
                    
                    // 检查货架是否在5分钟内已下发过任务
                    const shelf = shelfInput.value.trim();
                    if (shelf && shelfHistory[shelf] && (Date.now() - shelfHistory[shelf]) < 300000) {
                        shelfLock.style.display = 'block';
                        submitBtn.disabled = true;
                    } else {
                        shelfLock.style.display = 'none';
                        submitBtn.disabled = false;
                    }
                } else {
                    shelfGroup.style.display = 'none';
                    submitBtn.disabled = false;
                }
                
                // 显示或隐藏任务路径选择
                if (task.requires_task_path) {
                    taskPathGroup.style.display = 'block';
                    
                    // 填充任务路径选项
                    taskPathSelect.innerHTML = '<option value="">请选择任务路径</option>';
                    task.task_path_options.forEach(path => {
                        const option = document.createElement('option');
                        option.value = path;
                        option.textContent = path;
                        taskPathSelect.appendChild(option);
                    });
                } else {
                    taskPathGroup.style.display = 'none';
                }
            } else {
                shelfGroup.style.display = 'none';
                taskPathGroup.style.display = 'none';
                submitBtn.disabled = false;
            }
        }

        // 提交任务
        function submitTask() {
            const area = areaSelect.value;
            const taskName = taskSelect.value;
            
            if (!area) {
                alert('请选择区域');
                return;
            }
            
            if (!taskName) {
                alert('请选择任务模板');
                return;
            }
            
            const task = config.areas[area].tasks[taskName];
            const shelf = shelfInput.value.trim();
            
            // 验证货架号
            if (task.requires_shelf && !shelf) {
                shelfError.style.display = 'block';
                return;
            }
            
            // 验证任务路径
            if (task.requires_task_path && !taskPathSelect.value) {
                taskPathError.style.display = 'block';
                return;
            }
            
            // 检查货架是否在5分钟内已下发过任务
            if (task.requires_shelf && shelfHistory[shelf] && (Date.now() - shelfHistory[shelf]) < 300000) {
                shelfLock.style.display = 'block';
                return;
            }
            
            // 准备请求数据
            const requestData = [{
                modelProcessCode: task.code,
                priority: 6,
                orderId: `pad_html${new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')}`,
                fromSystem: "pad-html",
                taskOrderDetail: {
                    taskPath: task.requires_task_path ? taskPathSelect.value : "",
                    shelfNumber: task.requires_shelf ? shelf : ""
                }
            }];
            
            // 显示调试信息
            debugInfo.textContent = JSON.stringify(requestData, null, 2);
            
            // 发送请求
            submitBtn.disabled = true;
            submitBtn.textContent = '下发中...';
            
            fetch(task.base_url || config.areas[area].base_url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                // 显示响应信息
                responseBox.style.display = 'block';
                responseBox.textContent = JSON.stringify(data, null, 2);
                
                if (data.code === 1000) {
                    // 成功处理
                    successModal.style.display = 'flex';
                    
                    // 记录货架下发时间
                    if (task.requires_shelf && shelf) {
                        shelfHistory[shelf] = Date.now();
                    }
                }
            })
            .catch(error => {
                responseBox.style.display = 'block';
                responseBox.textContent = `请求失败: ${error.message}`;
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.textContent = '下发任务';
            });
        }

        // 切换调试信息显示
        function toggleDebugInfo() {
            if (debugInfo.style.display === 'block') {
                debugInfo.style.display = 'none';
                debugToggle.textContent = '查看发送的报文';
            } else {
                debugInfo.style.display = 'block';
                debugToggle.textContent = '隐藏发送的报文';
            }
        }

        // 关闭成功模态框
        function closeModal() {
            successModal.style.display = 'none';
        }

        // 切换主题
        function toggleTheme() {
            document.body.classList.toggle('dark-mode');
            localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
        }

        // 货架输入变化时检查锁定状态
        shelfInput.addEventListener('input', function() {
            const area = areaSelect.value;
            const taskName = taskSelect.value;
            
            if (area && taskName && config.areas[area] && config.areas[area].tasks[taskName]) {
                const task = config.areas[area].tasks[taskName];
                
                if (task.requires_shelf) {
                    const shelf = shelfInput.value.trim();
                    
                    if (shelf && shelfHistory[shelf] && (Date.now() - shelfHistory[shelf]) < 300000) {
                        shelfLock.style.display = 'block';
                        submitBtn.disabled = true;
                    } else {
                        shelfLock.style.display = 'none';
                        submitBtn.disabled = false;
                    }
                }
            }
        });

        // 初始化页面
        document.addEventListener('DOMContentLoaded', initPage);
    </script>
</body>
</html>